package foxmob.mooc.wx;

/**
 * Created by liyusen on 2017/5/25.
 */



import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import org.jooq.util.derby.sys.Sys;
import spark.Request;
import spark.Response;
import me.chanjar.weixin.mp.api.*;
import me.chanjar.weixin.mp.api.impl.*;
import me.chanjar.weixin.mp.bean.message.*;
import me.chanjar.weixin.mp.bean.menu.*;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import foxmob.mooc.AppCfg;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;


import static spark.Spark.get;
import static spark.Spark.post;

public class Handler {
    protected static WxMpInMemoryConfigStorage config;
    protected static WxMpService wxMpService;
    protected static WxMpMessageRouter wxMpMessageRouter;
    public static void  init(){
        config = new WxMpInMemoryConfigStorage();
        config.setAppId(AppCfg.sWxUser); // 设置微信公众号的appid
        config.setSecret(AppCfg.sWxKey); // 设置微信公众号的app corpSecret
        config.setToken(AppCfg.sWxToken); // 设置微信公众号的token
        config.setAesKey(AppCfg.sWxAesKey); // 设置微信公众号的EncodingAESKey

        wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(config);


        get("/wx", Handler::auth);
        post("/wx",Handler::dispatch);
        get("/wx/menu",Handler::updateMenu);


    }
    public static String auth(Request req, Response res){
        String signature = req.raw().getParameter("signature");
        String nonce = req.raw().getParameter("nonce");
        String timestamp = req.raw().getParameter("timestamp");

        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            // 消息签名不正确，说明不是公众平台发过来的消息

            return "none";
        }

        return  req.raw().getParameter("echostr");




    }
    public static String dispatch(Request req,Response res){
        try{
            System.out.println("testing:");
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(req.raw().getInputStream());
            WxMpXmlOutMessage outMsg = WxMpXmlOutMessage.TEXT().content("reply:"+inMessage.getContent()).fromUser(
                    inMessage.getToUser()).toUser(inMessage.getFromUser()).build();
            System.out.println("received:");
            System.out.println(inMessage.getContent());


            return outMsg.toXml().toString();


        }
        catch(Exception e) {
            return "sth wrong";

        }



    }

    public static String updateMenu(Request req, Response res){
        try{
            WxMenu menu = new WxMenu();
            WxMenuButton wb= new WxMenuButton();
            wb.setName("test");
            List<WxMenuButton> buttons = new ArrayList<WxMenuButton>();
            buttons.add(wb);
            menu.setButtons(buttons);

            wxMpService.getMenuService().menuCreate(menu);

        }catch (Exception e){
            return "fail";

        }


        return "";
    }
}
